﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AlertSystem.PluggableModules;
using AlertSystem.Business;
using System.Net.Mail;
using System.ComponentModel;
using Utils;

namespace AlertSystem.SendEmail
{
    public class SendAlert : WorkingBaseSendAlert
    {
        #region properties
        public string SmtpServer { get { return GetConfig("SmtpServer"); } set { SetConfig("SmtpServer", value); } }
        public int SmtpPort { get { return GetConfig("SmtpPort").ToInt(); } set { SetConfig("SmtpPort", value.ToString()); } }
        public string EmailAddress { get { return GetConfig("EmailAddress"); } set { SetConfig("EmailAddress", value); } }
        public string EmailPassword { get { return GetConfig("EmailPassword"); } set { SetConfig("EmailPassword", value); } }
        public string EmailSubject { get { return GetConfig("EmailSubject"); } set { SetConfig("EmailSubject", value); } }
        #endregion properties
       
        protected override void Send(Warning_Message msg, List<Warning_Account_Method> accountMethods)
        {
            try
            { 
                string ricipients = string.Join(",", accountMethods.Select(p => p.Account_Config));
                SmtpClient smtpMail = new SmtpClient(SmtpServer, SmtpPort);
                smtpMail.UseDefaultCredentials = false;
                smtpMail.Credentials = new System.Net.NetworkCredential(EmailAddress, EmailPassword);
                smtpMail.EnableSsl = true;
                smtpMail.SendCompleted += new SendCompletedEventHandler(SmtpMail_SendCompleted);
                smtpMail.SendAsync(EmailAddress, ricipients, EmailSubject, msg.Message, null);
            }
            catch (Exception ex)
            {
                Warning_Log.InsertLog(ex);
            }
        }

        private void SmtpMail_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                    throw e.Error;
            }
            catch (Exception ex)
            {
                Warning_Log.InsertLog(ex);
            }
            finally
            {
                SmtpClient smtp = (SmtpClient)sender;
                if (smtp != null)
                    smtp.Dispose();
            }
        }
    }
}